package com.yunji.hushuang.common;

import java.beans.Transient;
import java.io.Serializable;

/**
 * 响应消息体
 *
 * @author hushuang
 * @since 2019/11/5
 */
public class DataResponse<T> implements Serializable {

    private static final int SUCCESS_CODE = 0;
    private static final int DEFAULT_FAIL_CODE = 1;

    private int code;
    private String message;
    private T data;

    public DataResponse() {
        this.code = SUCCESS_CODE;
        this.message = "";
    }

    public static DataResponse success() {
        return success("请求成功", null);
    }

    public static DataResponse success(String message) {
        return success(message, null);
    }

    public static <T> DataResponse<T> success(T data) {
        return success("请求成功", data);
    }

    public static <T> DataResponse<T> success(String message, T data) {
        DataResponse<T> dataResponse = new DataResponse<>();
        dataResponse.message = message;
        dataResponse.data = data;
        return dataResponse;
    }

    public static DataResponse fail() {
        return fail(DEFAULT_FAIL_CODE, "请求失败");
    }

    public static DataResponse fail(String message) {
        return fail(DEFAULT_FAIL_CODE, message);
    }

    public static DataResponse fail(int code, String message) {
        if (code == SUCCESS_CODE) {
            throw new IllegalArgumentException("Fail response code == 0 is not allowed !");
        }
        DataResponse dataResponse = new DataResponse();
        dataResponse.code = code;
        dataResponse.message = message;
        return dataResponse;
    }

    @Transient
    public boolean isSuccess() {
        return getCode() == SUCCESS_CODE;
    }

    @Transient
    public boolean isFail() {
        return !isSuccess();
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    public T getData() {
        return data;
    }
}
